<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        
        .father {
            position: relative;
            width: 200px;
            height: 200px;
            background-color: pink;
            margin: 100px;
        }
        
        .son {
            width: 100px;
            height: 100px;
            background-color: skyblue;
            margin: 40px;
        }
        
        .w {
            width: 120px;
            height: 120px;
            background-color: red;
            margin: 0 auto 200px;
            padding: 10px;
            border: 15px solid black;
        }
    </style>
</head>

<body>
    <div class="father">
        <div class="son"></div>
    </div>

    <div class="w"></div>
    <br>
    <br>
    <img src="offset概述.png" alt="">
    <br>
    <img src="offset与style的区别.png" alt="">
    <script>
        // offset系列
        // 1. offsetTop 距离顶部 offsetLeft 距离左边 (可以动态获取)
        // 以带有定位的父视图为准 如果没有父视图或父视图没有定位则以浏览器为主
        var father = document.querySelector('.father');
        var son = document.querySelector('.son');
        console.log(father.offsetTop);
        console.log(father.offsetLeft);
        console.log(son.offsetLeft);

        // 2. 获取元素的大小 宽度和高度 是包含 padding + border + width
        var w = document.querySelector('.w');
        console.log(w.offsetWidth);
        console.log(w.offsetHeight);

        // 3. 获取子视图带有定位的父视图 否则返回body
        console.log(son.offsetParent); // 父视图必须存在定位
        console.log(w.offsetParent);
        console.log(son.parentNode); // 返回最近一级的父视图 不管父视图是否存在定位

        // 获取鼠标在w盒子内点击的坐标
        w.addEventListener('mousemove', function(e) {
            // console.log(e.pageX);
            // console.log(e.pageY);
            // console.log(w.offsetLeft);
            // console.log(w.offsetTop);
            var x = e.pageX - this.offsetLeft;
            var y = e.pageY - this.offsetTop;
            w.innerHTML = x + '-----' + y;
        });
    </script>
</body>

</html>